use serde::Deserialize;

#[derive(Deserialize, Debug, Clone)]
pub struct Config {
    pub app: App,
    pub database: Database,
    pub server: Server,
    pub log: Log,
}

#[derive(Deserialize, Debug, Clone)]
pub struct App {
    pub name: String,
}

#[derive(Deserialize, Debug, Clone)]
pub struct Database {
    pub url: String,
    pub max_connections: u32,
    pub min_connections: u32,
    pub connect_timeout: u32,
    pub idle_timeout: u32,
    pub max_lifetime: u32,
    pub sqlx_logging: bool,
    pub sqlx_logging_level: Level,
}

#[derive(Deserialize, Debug, Clone, Copy)]
pub enum Level {
    Off,
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

#[derive(Debug, Deserialize, Clone)]
pub struct Server {
    pub address: String,
    pub port: u32,
    pub cross_domain_white_list: Vec<String>,
}

#[derive(Deserialize, Debug, Clone)]
pub struct Log {
    pub path: String,
}

impl Config {
    pub fn read_config(path: &str) -> anyhow::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let config = toml::from_str::<Config>(&content)?;
        Ok(config)
    }
}
